package com.adulcimer.core.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaResponse;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.util.SaResult;
import com.adulcimer.core.common.JacksonObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author Simon
 * @create 2025/7/18
 * @Description
 **/

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080",  "http://localhost:5173")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }

    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                .setError(e -> SaResult.error(e.getMessage()))
                .setBeforeAuth(obj -> {
                    SaResponse response = SaHolder.getResponse();
                    // 动态设置Allow-Origin为请求的实际Origin，而不是*
                    String origin = SaHolder.getRequest().getHeader("Origin");
                    if (origin != null && (origin.equals("http://172.16.0.152") || origin.equals("http://172.16.0.152:80") ||
                            origin.equals("http://172.16.0.152:5174") || origin.equals("http://localhost:5174"))) {
                        response.setHeader("Access-Control-Allow-Origin", origin);
                    }
                    response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
                    response.setHeader("Access-Control-Allow-Headers", "*");
                    response.setHeader("Access-Control-Allow-Credentials", "true");
                    response.setHeader("Access-Control-Max-Age", "3600");

                    // 处理OPTIONS预检请求 - 确保正确处理
                    SaRouter.match(SaHttpMethod.OPTIONS)
                            .free(r -> {
                                System.out.println("--------OPTIONS预检请求，不做处理");
                                // 添加必要的CORS头到预检响应
                                response.setHeader("Access-Control-Allow-Origin", origin);
                                response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
                                response.setHeader("Access-Control-Allow-Headers", "*");
                                response.setHeader("Access-Control-Allow-Credentials", "true");
                                response.setHeader("Access-Control-Max-Age", "3600");
                            })
                            .back(SaResult.ok());
                });
    }


    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {

        // 创建自定义的消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

        // 设置自定义的JSON解析器
        messageConverter.setObjectMapper(new JacksonObjectMapper());

        // 将消息转换器添加到集合中
        converters.add(1, messageConverter);

    }

}